# coding: utf-8
import atexit

from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vmodl
from pyVmomi import vim
import ssl

ssl._create_default_https_context = ssl._create_unverified_context


class GetVMInfo(object):
    def __init__(self, host, user, password, port=443,):
        self.host = host
        self.port = port
        self.user = user
        self.pwd = password
        self.content = None
        # self.connect()

    def connect(self):
        try:
            service_instance = SmartConnect(host=self.host,
                                   user=self.user,
                                   pwd=self.pwd,
                                   port=int(self.port))
            atexit.register(Disconnect, service_instance)
        except vim.fault.InvalidLogin:
            raise SystemExit("Unable to connect to host "
                             "with supplied credentials.")

        self.content = service_instance.RetrieveContent()
        try:
            container = self.content.rootFolder  # starting point to look into
            viewType = [vim.VirtualMachine]  # object types to look for
            recursive = True  # whether we should look into it recursively
            container_view = self.content.viewManager.CreateContainerView(
                container, viewType, recursive)
            return container_view.view
        except vmodl.MethodFault as error:
            print("Caught vmodl fault : " + error.msg)
            return -1

    def get_vm_list(self):
        children = self.connect()
        vm_count = len(children)
        detail_all = {"vm_count": vm_count}
        off_count = 0
        for vm in children:
            state, data = self.vminfo_to_dict(vm)
            detail_all[vm.name] = data
            if state == 'poweredOff':
                off_count += 1
        detail_all["off_count"] = off_count
        return detail_all

    @staticmethod
    def vminfo_to_dict(vm):
        summary = vm.summary
        detail_info = {
            "name": summary.config.name,
            "template": summary.config.template,
            "path": summary.config.vmPathName,
            "guest": summary.config.guestFullName,
            "Instance UUID": summary.config.instanceUuid,
            "Bios UUID": summary.config.uuid,
            "Annotation": summary.config.annotation,
            "IP": summary.guest.ipAddress,
            "Question": summary.runtime.question,
            "State":  summary.runtime.powerState,
            "connectionState": summary.runtime.connectionState
        }

        return detail_info["State"], detail_info


if __name__ == "__main__":
    host = '10.33.64.125'
    user = 'root'
    password = '1234567'
    v = GetVMInfo(host, user, password)
    print v.get_vm_list()
    print v.get_vm_list()